<template>
  <BaseForm v-model="formDataModel" @close="$emit('callBack')" />

</template>

<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import AssistCheckInfoApi from '/@/api/webPath/AssistCheckInfoApi.ts';
import { translate } from "/@/i18n";
import FORM_FIELD_TYPE from "/@/constants/FormFieldType.ts";
import AssistCheckTemplateApi from '~/src/api/webPath/AssistCheckTemplateApi';
import { ref } from 'vue'
import { Input } from 'postcss';
defineOptions({
  name: 'AssistCheckInfoEdit',
})
const props = defineProps({
  modelValue: {

  }
})
const emit = defineEmits(['fetch-data', 'callBack'])

const formRef = ref<FormInstance>();
const title = ref<string>('');
const dialogFormVisible = ref<boolean>(false);
const checkType = ref()

// 时间  日期
// 创建一个 Date 对象，表示当前时间
const now = new Date();
// 获取年份
const year = now.getFullYear(); // 获取完整的年份（例如：2023）
// 获取月份
const month = now.getMonth() + 1; // 获取月份（0-11，0 表示 1 月，所以需要 + 1）
// 获取日期
const day = now.getDate(); // 获取日期（1-31）
// 获取小时
const hours = now.getHours(); // 获取小时（0-23）
// 获取分钟
const minutes = now.getMinutes(); // 获取分钟（0-59）
// 获取秒数
const seconds = now.getSeconds(); // 获取秒数（0-59）
// 格式化年月日
const yearMonthDay = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
// 格式化时分秒
const hoursMinutesSeconds = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
// 当前的时分秒
const dateTime = `${yearMonthDay} ${hoursMinutesSeconds}`;
const defaultDateRange = ref<string[]>([]); // 修改：使用 ref 来存储日期范围
// interface FormDataModelData {
//   [key: string]: any; // 允许任意字符串 key 和 any 类型的值
// }

// 获取当前登录用户用户名
const userInfo = localStorage.getItem("advisory_company_userInfo")
const currentUserName = ref("")
if (userInfo) {
  const userInfoObj = JSON.parse(userInfo)
  currentUserName.value = userInfoObj.username
}

async function generateFeilds() {
  let data: any[] = []
  // if (props.modelValue.query && props.modelValue.query.assistCheckInfoId) {
  //   data = (await AssistCheckInfoApi.getDetailPageData({ checkId: props.modelValue.query.assistCheckInfoId })).data
  //   data = data && data.records
  // }
  if (checkType.value) {
    data = (await AssistCheckTemplateApi.templateList({ checkType: checkType.value })).data
    console.log("template list", data)
  }
  console.log(" current data:", data)
  const checkFieldItems: any[] = []
  data.forEach((x: any, index: number) => {
    console.log("current isStandardList", x.isStandardList)
    checkFieldItems.push(...[
      {
        title: `${x.checkSerial}.${x.checkItem}-${x.checkKey}`,
        expandColumn: true,
        type: FORM_FIELD_TYPE.TITLE,
        labelField: true
      },
      {
        field: `id-${index}`,
        value: x.id,
        isShow: () => false,
        type: FORM_FIELD_TYPE.READONLY,
      },
      {
        field: `checkSerial-${index}`,
        value: x.checkSerial,
        isShow: () => false,
        type: FORM_FIELD_TYPE.READONLY,
      },
      {
        field: `checkItem-${index}`,
        value: x.checkItem,
        isShow: () => false,
        type: FORM_FIELD_TYPE.READONLY,
      },
      {
        field: `checkKey-${index}`,
        value: x.checkKey,
        isShow: () => false,
        type: FORM_FIELD_TYPE.READONLY,
      },
      {
        label: "是否符合",
        field: `checkResult-${index}`,
        type: FORM_FIELD_TYPE.SINGLE_LAYER_SELECT,
        defaultValue: "符合",
        options: x.isStandardList.map(x => ({ label: x, value: x })),
        // options: [
        //   {
        //     value: "是",
        //     label: "是"
        //   },
        //   {
        //     value: "否",
        //     label: "否"
        //   },
        //   {
        //     value: "不适用",
        //     label: "不适用"
        //   }
        // ],
        // ：添加 change 事件处理函数**
        callback: (handlers: any, value: any) => {
          console.log("current value", value)
          // 获取当前 index
          const currentIndex = index;
          // 如果选择的是 "符合" 或 "不适用"，则自动填写 "/"
          if (["符合", "不适用"].includes(value)) {
            handlers.updateParam(`question-${currentIndex}`, "/");
            handlers.updateParam(`director-${currentIndex}`, "/");
            handlers.updateParam(`solution-${currentIndex}`, "/");
            formDataModel.value.items.some(x => {
              if (x.field === `director-${currentIndex}` || x.field === `solution-${currentIndex}`) {
                if (x.config) {
                  x.config.disabled = true
                } else {
                  x.config = {
                    disabled: true
                  }
                }
              }
            })
            console.log("formDataModel.items", formDataModel.value.items)
          } else {
            // 如果选择的是 "不符合"，则清空这些字段
            handlers.updateParam(`question-${currentIndex}`, (x.problemList && x.problemList[0]) ?? "");
            handlers.updateParam(`director-${currentIndex}`, "");
            handlers.updateParam(`solution-${currentIndex}`, "");
            formDataModel.value.items.some(x => {
              if (x.field === `director-${currentIndex}` || x.field === `solution-${currentIndex}`) {
                if (x.config) {
                  x.config.disabled = false
                } else {
                  x.config = {
                    disabled: false
                  }
                }
              }
            })
            console.log("question-", `question-${index}`);
          }
        }
      },
      {
        label: "发现问题",
        field: `question-${index}`,
        defaultValue: "/",
        options: x.problemList?.map(x => ({ label: x, value: x })),
        inputType: "textarea",
        inputProps: {
          rows: 5
        },
        type: FORM_FIELD_TYPE.EDITABLE_SELECT,
      },
      {
        label: "整改负责人",
        defaultValue: "/",
        config: {
          disabled: true
        },
        field: `director-${index}`,
        type: FORM_FIELD_TYPE.INPUT,
      },
      {
        label: "整改措施落实情况",
        field: `solution-${index}`,
        config: {
          disabled: true,
        },
        defaultValue: "/",
        // inputType: "textarea",
        // inputProps: {
        //   rows: 5
        // },
        props: {
          row: 5
        },
        // options: x..map(x => ({ label: x, value: x })),
        // type: FORM_FIELD_TYPE.EDITABLE_SELECT,
        type: FORM_FIELD_TYPE.TEXTAREA
      }
    ])
  })
  console.log("checkFieldItems", checkFieldItems)
  const reviserNameField = checkType.value === 2 || checkType.value === 1 ? [{
    label: "检查人",
    expandColumn: true,
    field: 'director',
    defaultValue: currentUserName.value,
    type: FORM_FIELD_TYPE.INPUT,
  }] : []
  formDataModel.value.items = [...formDataModel.value.items.filter(x => x.fixed), ...reviserNameField, ...checkFieldItems]
}
// // 动态生成自查填写项目
// onBeforeMount(() => {
//   generateFeilds()
// })

const formDataModel = ref({
  columnCount: 1,
  expandLimit: 6,
  autoFit: false,
  columnWidth: '300px',
  labelPosition: 'right',
  labelWidth: '150px',
  modelData: {},  //表单参数值 初始化
  callback: async (any: object) => {  //表单执行成功后回调
    //完成数据提交

    const obj = {
      assistCheckInfo: {
        checkDate: `${any.checkDate} 00:00:00`,
        checkType: any.checkType,
        director: any.director,
      },
      list: []
    }

    if (props.modelValue.query && props.modelValue.query.assistCheckInfoId) {
      Object.assign(obj.assistCheckInfo, {
        id: props.modelValue.query.assistCheckInfoId
      })
    }

    if (checkType.value === 2) {
      Object.assign(obj.assistCheckInfo, {
        reviserName: any.reviserName
      })
    }
    for (const key of Object.keys(any)) {
      const keyList: string[] = ["id", "checkSerial", "checkResult", "question", "director", "solution", "checkItem", "checkKey"]
      const finalKeyList: string[] = [...keyList]
      console.log("props modelvalue query", props.modelValue.query)
      if (!props.modelValue.query || !props.modelValue.query.assistCheckInfoId) {
        finalKeyList.splice(0, finalKeyList.length + 1, ...keyList.filter(x => x !== "id"))
        console.log("finalKeyList", finalKeyList)
      }
      console.log("obj list", obj)
      if (finalKeyList.includes(key.split("-")[0])) {
        const [fieldName, index] = key.split("-")
        console.log("kkk key", key)
        const val = obj.list[+index]
        if (val !== undefined) {
          obj.list[+index][fieldName] = any[key]
        } else {
          obj.list[+index] = { [fieldName]: any[key] }
        }
      }
    }

    const { message } = await AssistCheckInfoApi.save(obj)
    $baseMessage(message, 'success', 'vab-hey-message-success');
    // const { message } = await AssistCheckInfoApi.save(any)
    //     $baseMessage(message, 'success', 'vab-hey-message-success');
    // dialogFormVisible.value = false


    //事件及数据推送到上一层父类
    emit('callBack', any); //把表单数据推送到上一层
  },
  items: [  //表单item数据初始化
    //           {
    //     label: "编号",
    //     field: "checkNo",
    //     clearable: true,
    //     type: FORM_FIELD_TYPE.INPUT,

    //    placeholder:"请输入",

    //    rule:{
    //      trigger: 'blur',
    //      validator: (rule: any, value: any, callback: any) => {  //绑定验证
    //            callback();
    //        },
    //      },

    // },
    {
      label: "自查日期",
      field: "checkDate",
      expandColumn: true,
      fixed: true,
      clearable: true,
      type: FORM_FIELD_TYPE.DATE,
      placeholder: "请输入",
      rule: {
        trigger: 'blur',
        validator: (rule: any, value: any, callback: any) => {  //绑定验证
          callback();
        },
      },

      config: {
        props: {   //日期精度配置
          type: "daterange",
          startPlaceholder: "开始日期",
          endPlaceholder: "结束日期",
          format: "YYYY-MM-DD",
        }
      },
      onChange: () => { },
    },
    {
      label: "自查类型",
      field: "checkType",
      expandColumn: true,
      fixed: true,
      clearable: true,
      type: FORM_FIELD_TYPE.SINGLE_LAYER_SELECT,
      callback(handlers: any, v: any) {
        checkType.value = v
        generateFeilds()
      },
      options: [
        {
          value: 1,
          label: "每日自查"
        },
        {
          value: 2,
          label: "全项自查"
        }
      ],

      placeholder: "请输入",

      rule: {
        trigger: 'blur',
        validator: (rule: any, value: any, callback: any) => {  //绑定验证
          callback();
        },
      },
      onChange: () => { },
    },
    // {
    //   label: "检查人",
    //   field: "director",
    //   clearable: true,
    //   type: FORM_FIELD_TYPE.INPUT,
    //   defaultValue: currentUserName.value,
    //   placeholder: "请输入",
    //   rule: {
    //     trigger: 'blur',
    //     validator: (rule: any, value: any, callback: any) => {  //绑定验证
    //       callback();
    //     },
    //   },

    // },
    //   {
    //     label: "序号",
    //     field: "checkSerial",
    //     clearable: true,
    //     type: FORM_FIELD_TYPE.INPUT,

    //    placeholder:"请输入",

    //    rule:{
    //      trigger: 'blur',
    //      validator: (rule: any, value: any, callback: any) => {  //绑定验证
    //            callback();
    //        },
    //      },

    // },
    //   {
    //     label: "自查要点",
    //     field: "checkKey",
    //     clearable: true,
    //     type: FORM_FIELD_TYPE.INPUT,

    //    placeholder:"请输入",

    //    rule:{
    //      trigger: 'blur',
    //      validator: (rule: any, value: any, callback: any) => {  //绑定验证
    //            callback();
    //        },
    //      },

    // },
    //   {
    //     label: "结果",
    //     field: "checkResult",
    //     clearable: true,
    //     type: FORM_FIELD_TYPE.SINGLE_LAYER_SELECT,
    //       options:[
    //         {
    //           value: 0,
    //           label: "不符合"
    //         },
    //         {
    //           value: 1,
    //           label: "符合"
    //         },
    //         {
    //           value: 2,
    //           label: "不适用"
    //         }
    //       ],



    //    placeholder:"请输入",

    //    rule:{
    //      trigger: 'blur',
    //      validator: (rule: any, value: any, callback: any) => {  //绑定验证
    //            callback();
    //        },
    //      },

    // },
    //   {
    //     label: "整改措施",
    //     field: "solution",
    //     clearable: true,
    //     type: FORM_FIELD_TYPE.INPUT,

    //    placeholder:"请输入",

    //    rule:{
    //      trigger: 'blur',
    //      validator: (rule: any, value: any, callback: any) => {  //绑定验证
    //            callback();
    //        },
    //      },

    // },
    //   {
    //     label: "负责人",
    //     field: "director",
    //     clearable: true,
    //     type: FORM_FIELD_TYPE.INPUT,

    //    placeholder:"请输入",

    //    rule:{
    //      trigger: 'blur',
    //      validator: (rule: any, value: any, callback: any) => {  //绑定验证
    //            callback();
    //        },
    //      },

    // },
    //   {
    //     label: "所属公司",
    //     field: "companyId",
    //     clearable: true,
    //     type: FORM_FIELD_TYPE.INPUT,

    //    placeholder:"请输入",

    //    rule:{
    //      trigger: 'blur',
    //      validator: (rule: any, value: any, callback: any) => {  //绑定验证
    //            callback();
    //        },
    //      },

    // },
    //   {
    //     label: "创建人",
    //     field: "creator",
    //     clearable: true,
    //     type: FORM_FIELD_TYPE.INPUT,

    //    placeholder:"请输入",

    //    rule:{
    //      trigger: 'blur',
    //      validator: (rule: any, value: any, callback: any) => {  //绑定验证
    //            callback();
    //        },
    //      },

    // },
    //   {
    //     label: "修改人",
    //     field: "reviser",
    //     clearable: true,
    //     type: FORM_FIELD_TYPE.INPUT,

    //    placeholder:"请输入",

    //    rule:{
    //      trigger: 'blur',
    //      validator: (rule: any, value: any, callback: any) => {  //绑定验证
    //            callback();
    //        },
    //      },

    // },
    //   {
    //     label: "排序",
    //     field: "sort",
    //     clearable: true,
    //     type: FORM_FIELD_TYPE.INPUTNUMBER,
    //     defaultValue: 0,

    //    placeholder:"请输入",

    //    rule:{
    //      trigger: 'blur',
    //      validator: (rule: any, value: any, callback: any) => {  //绑定验证
    //            callback();
    //        },
    //      },

    // },

  ],
})






//页面数据加载
onMounted(async () => {

  //初始化数据model
  if (props.modelValue.query) { //跳转过来时候有参数
    if (props.modelValue.query.assistCheckInfoId) {  //id存在则为编辑，加载网络数据，如上级页面带参数手动覆盖

      const { data } = await AssistCheckInfoApi.getDetail({
        assistCheckInfoId: props.modelValue.query.assistCheckInfoId   //从路由中获取参数
      })
      console.log("data ", data)
      const { checkType: _checkType, ...rest } = data
      const detailData = (await AssistCheckInfoApi.getDetailPageData({ checkId: props.modelValue.query.assistCheckInfoId, _size: 1000, _current: 1 })).data
      console.log("field list data", data)
      const detailList = detailData && detailData.records

      checkType.value = +_checkType
      await generateFeilds()

      const detailObj = {}
      for (const [index, item] of detailList.entries()) {
        for (const key of Object.keys(item)) {
          detailObj[`${key}-${index}`] = item[key]
          if (item["checkResult"] === "不符合") {
            formDataModel.value.items.some(x => {
              console.log("current field", x.field)
              if (x.field === `solution-${index}` || x.field === `director-${index}`) {
                console.log("current x", x)
                x.config = {
                  disabled: false
                }
              }
            })
          }
        }
      }
      const obj = { checkType: +_checkType, ...rest, ...detailObj }
      console.log("obj", obj)
      formDataModel.value.modelData = obj;
      console.log("1111111formDataModel.value modeldata", formDataModel.value.modelData)
    } else {
      //新增时候则用父类页面传参默认填充可根据业务修改
      for (const key in props.modelValue.query) {
        formDataModel.value.modelData[key] = props.modelValue.query[key]
      }
      // 修改：设置日期范围的默认值
      defaultDateRange.value = [yearMonthDay]; // 设置默认的日期范围为今天
      formDataModel.value.modelData.checkDate = defaultDateRange.value; // 将默认值赋给 modelData
    }
  }
})


//方法暴露区域  todo
defineExpose({

})

</script>
